package com.quick.proxy.client.handler.real;

import com.quick.proxy.core.config.ProxyConfig;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Description: 真实代理子通道处理程序
 * Author: 吃素不吃肉
 * Date: 2023/7/9
 *
 * @author 吃素不吃肉
 */
@Component
@Lazy
public class RealProxyChildChannelHandler extends ChannelInitializer<SocketChannel> {
    private static final EventExecutorGroup TRANS_GROUP = new DefaultEventExecutorGroup(16);
    private final ProxyConfig proxyConfig;
    private final RealProxyConnectHandler realProxyConnectHandler;
    private final RealProxyProtocolDisposeHandler realProxyProtocolDisposeHandler;
    private final RealProxyProtocolEncoder realProxyProtocolEncoder;
    private final RealProxyProtocolOutboundHandler realProxyProtocolOutboundHandler;

    public RealProxyChildChannelHandler(ProxyConfig proxyConfig, RealProxyConnectHandler realProxyConnectHandler, RealProxyProtocolDisposeHandler realProxyProtocolDisposeHandler, RealProxyProtocolEncoder realProxyProtocolEncoder, RealProxyProtocolOutboundHandler realProxyProtocolOutboundHandler) {
        this.proxyConfig = proxyConfig;
        this.realProxyConnectHandler = realProxyConnectHandler;
        this.realProxyProtocolDisposeHandler = realProxyProtocolDisposeHandler;
        this.realProxyProtocolEncoder = realProxyProtocolEncoder;
        this.realProxyProtocolOutboundHandler = realProxyProtocolOutboundHandler;
    }

    @Override
    protected void initChannel(SocketChannel arg0) {
        arg0.pipeline().addLast(new IdleStateHandler(proxyConfig.getReaderIdleTime(), proxyConfig.getWriterIdleTime(), proxyConfig.getAllIdleTime(), TimeUnit.SECONDS));
        arg0.pipeline().addLast(realProxyConnectHandler);
        arg0.pipeline().addLast(new RealProxyProtocolDecoder());
        arg0.pipeline().addLast(realProxyProtocolOutboundHandler);
        arg0.pipeline().addLast(realProxyProtocolEncoder);
        arg0.pipeline().addLast(TRANS_GROUP, realProxyProtocolDisposeHandler);
    }

}
